#include "qtexteditwidget.h"

#include "../../../libs/shared/property/qabstractproperty.h"
#include "../../../libs/shared/host/qabstracthost.h"
#include "../../../libs/core/undocommand/qpropertychangedundocommand.h"

#include <QKeyEvent>

QTextEditWidget::QTextEditWidget(QAbstractProperty *property, QUndoStack *stack, QWidget *parent):
    QLineEdit(parent),
    m_property(property),
    m_undo_stack(stack)
{
    setAttribute(Qt::WA_DeleteOnClose,true);
    setFocus();

    setAlignment(Qt::AlignCenter);
    setText(property->get_value().toString());
    selectAll();

    setFrame(false);
}

void QTextEditWidget::focusOutEvent(QFocusEvent *)
{
    if(text()!=m_property->get_value().toString())
    {
        QPropertyChangedUndoCommand* cmd=new QPropertyChangedUndoCommand(m_property->get_host()->get_uuid(),
                                                                         m_property->get_name(),
                                                                         m_property->get_value(),text());
        m_undo_stack->push(cmd);
    }

    close();
}

void QTextEditWidget::keyPressEvent(QKeyEvent *e)
{
    if(e->key()==Qt::Key_Return)
    {
        this->clearFocus();
    }
    else if(e->key()==Qt::Key_Escape)
    {
        setText(m_property->get_value().toString());
        this->clearFocus();
    }
    QLineEdit::keyPressEvent(e);
}
